function TraverseCopy {
    param(
        [Parameter(Mandatory=$true)]
        [String] $Source, # 源目录
        [Parameter(Mandatory=$true)]
        [String] $Destination, # 目标目录
        [Parameter(Mandatory=$true)]
        [String] $Filter, # 筛选器
        [bool] $ExcludeMode = $false
    )

    # 如果指定了排除模式，则要求Filter不为空
    if($ExcludeMode -and $Filter.Length -eq 0) {
        Write-Output "No Filter given in exclude mode!!"
        return
    }

    $Filters = $Filter.Split(',');

    # 检查源目录是否存在
    if (!(Test-Path -Path $Source)) {
        Write-Error -Message "The source directory '$Source' was not exists!!"
        return
    }

    # 检查目标目录是否存在
    if (!(Test-Path -Path $Destination)) {
        # Write-Output "Creating directory '$Destination'"
        New-Item -ItemType Directory -Path $Destination | Out-Null
    }

    # 遍历源目录，获取需要的文件
    Get-ChildItem -Path $Source -Recurse -File |
        Where-Object {
            if ($ExcludeMode) {
                $_.Extension -notin $Filters
            }
            else {
                $_.Extension -in $Filters
            }
        } |
        ForEach-Object {
            $RelPath = $_.FullName.Substring($Source.Length+1)
            $TargetPath = Join-Path $Destination $RelPath
            $TargetDir = Split-Path $TargetPath -Parent

            # 确保目标目录存在
            if (!(Test-Path -Path $TargetDir)) {
                New-Item -ItemType Directory -Path $TargetDir | Out-Null
            }

            Copy-Item -Path $_.FullName -Destination $TargetPath
        }
}

function GetAppVersion {
    param(
        [Parameter(Mandatory=$true)]
        [String] $ExePath
    )
    if (!(Test-Path -Path $ExePath -PathType Leaf)) {
        Write-Error "Not a file: '$ExePath'"
    }
    $bytes=[System.IO.File]::ReadAllBytes($ExePath)
    $text=[System.Text.Encoding]::ASCII.GetString($bytes)
    $pos=$text.IndexOf("`$`$`$<ver>")
    if ($pos -ne -1) {
        $end_pos=$text.IndexOf("</ver>`$`$`$", $pos)
        $some_text = $text.Substring($pos + 8, $end_pos - $pos - 8);
        return $some_text
    }
    return "Unknown"
}

function ZipDirectory {
    param(
        [Parameter(Mandatory=$true)]
        [String] $Source,
        [String] $FileName = $(Split-Path -Path $Source -Leaf)
    )
    Write-Output "Compress ${Source} to ${FileName}.zip"
    Compress-Archive -Path "${Source}\*" -DestinationPath "${FileName}.zip" -Force -CompressionLevel Optimal
}

$ReleaseBinDir="C:\Users\tangguoli\Desktop\Workspace\DiaryToolpp\build\bin\Release"
$PackagesRoot="C:\Users\tangguoli\Desktop\Workspace\DiaryToolpp\build\packages"

$DateStr = (Get-Date).ToString("yyyyMMdd_HHmmss")
$AppVerStr = $(GetAppVersion "$ReleaseBinDir/DiaryApp.exe")

$WorkingTempDir="DiaryAppPkg-$DateStr"
$AppPkgDir="$WorkingTempDir/App"
$DbgPkgDir="$WorkingTempDir/Dbg"
$SaveDir="$PackagesRoot/DiaryApp_$AppVerStr"

# 创建保存目录，如果不存在的话
if (!(Test-Path -Path $SaveDir)) {
    New-Item -ItemType Directory -Path $SaveDir | Out-Null
}

Write-Output "Packaging App, Version $AppVerStr"
# 拷贝文件到App目录，排除pdb文件
TraverseCopy -Source $ReleaseBinDir -Destination $AppPkgDir -Filter ".pdb,.zip,.bat,.ps1" -ExcludeMode $true
# 创建压缩包
ZipDirectory -Source $AppPkgDir -FileName "${SaveDir}/DiaryApp_${AppVerStr}"

Write-Output "Packaging App Debug Infos"
# 拷贝文件到Dbg目录，只要pdb文件
TraverseCopy -Source $ReleaseBinDir -Destination $DbgPkgDir -Filter ".pdb" -ExcludeMode $false
# 创建压缩包
ZipDirectory -Source $DbgPkgDir -FileName "${SaveDir}/DiaryApp_${AppVerStr}_Debug"

# 删除临时文件目录
Remove-Item -Force $WorkingTempDir -Recurse
